<template>
    <div class='zgn-tabs-wrapper'>
        <div class='zgn-tabs-title' ref='container'>
            <div class="zgn-tabs-nav"
                :class="{selected:t===selected}"
                @click="isSelected(t)"
                v-for="(t,index) in titles" :key="index"
                :ref="el=>{if(el) navItems[index] = el}">
                {{t}}
            </div>
            <div class="zgn-tabs-nav-indicator" ref="indicator"></div>
        </div>
        <div  v-for="(c,index ) in defaults" :key="index" >
            <component class='zgn-tabs-content' v-if="c.props.title===selected" :is="c"></component>
        </div>
    </div>
</template>

<script lang="ts">
import Tab from './Tab.vue'
import { ref,onMounted,onUpdated } from 'vue';

export default {
    setup(props,ctx){
        const navItems = ref<HTMLDivElement[]>([])
        const indicator=ref<HTMLDivElement>(null)
        const container=ref<HTMLDivElement>(null)
        const x=()=>{
            const divs=navItems.value
            const result = divs.filter(div=>div.classList.contains('selected'))[0]
            const {width} =result.getBoundingClientRect()
            indicator.value.style.width=width+'px'
            const {left:left1} = container.value.getBoundingClientRect()
            const {left:left2} = result.getBoundingClientRect()
            const left = left2-left1
            indicator.value.style.left=left+'px'
        }
        onMounted(x)
        onUpdated(x)
        const defaults = ctx.slots.default()// 这句代码可以获取内部子组件的内容
        let  selected=ref(defaults[0].props.title)
        defaults.forEach(item => {
            if(item.type!==Tab){
                throw new Error('Tabs 子组件必须是Tab')
            }
        })
        const titles = defaults.map(item=>{
           return item.props.title
        })
        const isSelected=(t:string)=>{
            selected.value = t
        }
        return {
            defaults,titles,selected,isSelected,navItems,indicator,container
        }
    }
}
</script>

<style lang="scss" >
.zgn-tabs-wrapper{
    padding:10px;
    >.zgn-tabs-title{
        display:flex;
        position: relative;
        >.zgn-tabs-nav{
            font-weight:700;
            margin-right:20px ;
           
        }
    }
    
}
.zgn-tabs-content{
    border-top: 1px solid rgb(180, 173, 173);
    margin-top: 10px;
    padding: 10px;
}
.selected{
   color: rgb(66, 66, 221);

}
.zgn-tabs-nav-indicator{
    position: absolute;
    height: 3px;
    background:rgb(66, 66, 221);
    left: 0px;
    bottom:-10px;
    width:100px;
    transition: all 250ms;
}

</style>